// 配置
const CONFIG = {
    CACHE_ENABLED: true,
    LOCAL_MODEL_FILE: 'sample.glb',
    LOADING_DELAY: 2000 // 模拟加载延迟（毫秒）
};

// 3D模型查看器
class ModelViewer {
    constructor(containerId) {
        this.container = document.getElementById(containerId);
        this.scene = null;
        this.camera = null;
        this.renderer = null;
        this.controls = null;
        this.currentModel = null;
        this.initThreeJS();
    }

    initThreeJS() {
        try {
            // 创建场景
            this.scene = new THREE.Scene();
            this.scene.background = new THREE.Color(0xf8f9fa);

            // 创建相机
            const width = this.container.clientWidth || 800;
            const height = this.container.clientHeight || 450;
            this.camera = new THREE.PerspectiveCamera(75, width / height, 0.1, 1000);
            this.camera.position.set(0, 2, 5);

            // 创建渲染器
            this.renderer = new THREE.WebGLRenderer({ antialias: true, alpha: true });
            this.renderer.setSize(width, height);
            //this.renderer.setSize(this.container.clientWidth, this.container.clientHeight);
            //this.renderer.setPixelRatio(window.devicePixelRatio); // 适配高清屏

            this.renderer.shadowMap.enabled = true;
            this.renderer.shadowMap.type = THREE.PCFSoftShadowMap;
            this.container.innerHTML = '';
            this.container.appendChild(this.renderer.domElement);

            // 轨道控制器
            this.controls = new THREE.OrbitControls(this.camera, this.renderer.domElement);
            this.controls.enableDamping = true;
            this.controls.dampingFactor = 0.05;
            this.controls.screenSpacePanning = false;
            this.controls.minDistance = 1;
            this.controls.maxDistance = 50;

            // 灯光
            const ambientLight = new THREE.AmbientLight(0xffffff, 0.6);
            this.scene.add(ambientLight);
            const directionalLight = new THREE.DirectionalLight(0xffffff, 0.8);
            directionalLight.position.set(10, 20, 15);
            directionalLight.castShadow = true;
            directionalLight.shadow.mapSize.width = 2048;
            directionalLight.shadow.mapSize.height = 2048;
            this.scene.add(directionalLight);

            // 网格辅助
            const gridHelper = new THREE.GridHelper(10, 10, 0x000000, 0x000000);
            gridHelper.material.opacity = 0.2;
            gridHelper.material.transparent = true;
            this.scene.add(gridHelper);

            // 窗口自适应
            window.addEventListener('resize', () => this.onWindowResize());

            // 启动动画循环
            this.animate();

            console.log('✅ Three.js初始化完成');
        } catch (error) {
            console.error('❌ Three.js初始化失败:', error);
        }
    }

    onWindowResize() {
        const width = this.container.clientWidth || 800;
        const height = this.container.clientHeight || 450;
        this.camera.aspect = width / height;
        this.camera.updateProjectionMatrix();
        this.renderer.setSize(width, height);
    }

    animate() {
        requestAnimationFrame(() => this.animate());
        if (this.controls) this.controls.update();
        this.renderer.render(this.scene, this.camera);
    }

    async loadModel(url) {
        return new Promise((resolve, reject) => {
            try {
                // 清理旧模型
                if (this.currentModel) {
                    this.scene.remove(this.currentModel);
                    this.currentModel = null;
                }

                const loader = new THREE.GLTFLoader();
                loader.load(
                    url,
                    (gltf) => {
                        const model = gltf.scene;

                        // 开启阴影
                        model.traverse((child) => {
                            if (child.isMesh) {
                                child.castShadow = true;
                                child.receiveShadow = true;
                                // 如果模型材质为黑色，可以强制标准材质
                                if (!(child.material instanceof THREE.MeshStandardMaterial)) {
                                    child.material = new THREE.MeshStandardMaterial({ color: 0xaaaaaa });
                                }
                            }
                        });

                        this.scene.add(model);
                        this.currentModel = model;

                        // 调整相机
                        const box = new THREE.Box3().setFromObject(model);
                        const center = box.getCenter(new THREE.Vector3());
                        const size = box.getSize(new THREE.Vector3());
                        // 计算底部位置
                        const minY = box.min.y;

                        // 将模型整体向上移动，让底部在 y=0
                        model.position.y -= minY;

                        
                        const maxDim = Math.max(size.x, size.y, size.z);
                        const fov = this.camera.fov * (Math.PI / 180);
                        let cameraZ = Math.abs(maxDim / Math.sin(fov / 2)) * 1.5;
                        this.camera.position.z = cameraZ;
                        // this.controls.target.copy(center);

                        // 设置 OrbitControls 目标在模型底部中心
                        this.controls.target.set(center.x, center.y - minY, center.z);
                        this.controls.update();

                        // this.controls.update();

                        resolve();
                    },
                    (progress) => {
                        const percent = progress.loaded / progress.total * 100;
                        this.updateLoadingStatus(`加载模型: ${percent.toFixed(1)}%`);
                    },
                    (error) => {
                        console.error('模型加载失败:', error);
                        reject(error);
                    }
                );
            } catch (error) {
                reject(error);
            }
        });
    }

    updateLoadingStatus(message) {
        const el = document.getElementById('loading-status');
        if (el) el.textContent = message;
    }
}

// 本地模型生成器
class LocalModelGenerator {
    static async generateModel(type, input) {
        await this.simulateProcessing(type, input);
        return CONFIG.LOCAL_MODEL_FILE;
    }

    static async simulateProcessing(type, input) {
        const steps = [
            '分析输入内容...',
            '理解需求...', 
            '生成3D结构...',
            '优化网格...',
            '添加纹理...',
            '最终渲染...'
        ];
        for (let step of steps) {
            await new Promise(res => setTimeout(res, 300));
            this.updateLoadingStatus(step);
        }
    }

    static updateLoadingStatus(msg) {
        const el = document.getElementById('loading-status');
        if (el) el.textContent = msg;
    }
}

// 主应用
class App {
    constructor() {
        this.viewer = new ModelViewer('model-container');
        this.currentTab = 'text-tab';
        this.currentModelUrl = null;
        this.setupEventListeners();
    }

    setupEventListeners() {
        // 标签切换
        document.querySelectorAll('.tab-button').forEach(btn => {
            btn.addEventListener('click', (e) => this.switchTab(e.target.dataset.tab));
        });

        // 文本生成
        document.getElementById('generate-from-text').addEventListener('click', () => {
            const text = document.getElementById('text-input').value.trim();
            if (!text) return alert('请输入描述文本！');
            this.generateModel('text', text);
        });

        // 图片生成
        const imgBtn = document.getElementById('generate-from-image');
        document.getElementById('generate-from-image').addEventListener('click', () => {
            const file = document.getElementById('file-input').files[0];
            if (!file) return alert('请选择图片！');
            this.generateModel('image', file);
        });

        // 下载
        document.getElementById('download-btn').addEventListener('click', () => this.downloadModel());

        // 反馈
        document.getElementById('feedback-good').addEventListener('click', () => this.recordFeedback('good'));
        document.getElementById('feedback-bad').addEventListener('click', () => this.recordFeedback('bad'));

        // 文件上传和拖拽
        this.setupFileUpload();
    }

    setupFileUpload() {
        const fileInput = document.getElementById('file-input');
        const dropZone = document.getElementById('drop-zone');
        const generateBtn = document.getElementById('generate-from-image');

        fileInput.addEventListener('change', (e) => this.handleFileSelect(e));

        dropZone.addEventListener('dragover', (e) => {
            e.preventDefault();
            dropZone.style.borderColor = '#3498db';
            dropZone.style.background = '#ecf0f1';
        });

        dropZone.addEventListener('dragleave', () => {
            dropZone.style.borderColor = '#bdc3c7';
            dropZone.style.background = 'white';
        });

        dropZone.addEventListener('drop', (e) => {
            e.preventDefault();
            dropZone.style.borderColor = '#bdc3c7';
            dropZone.style.background = 'white';
            if (e.dataTransfer.files.length) {
                fileInput.files = e.dataTransfer.files;
                this.handleFileSelect({ target: fileInput });
            }
        });
    }

    handleFileSelect(e) {
        const file = e.target.files[0];
        if (!file || !file.type.match('image.*')) return alert('请上传图片文件！');
        const preview = document.getElementById('image-preview');
        const generateBtn = document.getElementById('generate-from-image');
        const reader = new FileReader();
        reader.onload = (e) => {
            preview.innerHTML = `<img src="${e.target.result}" alt="预览">`;
            generateBtn.disabled = false;
        };
        reader.readAsDataURL(file);
    }

    switchTab(tabId) {
        document.querySelectorAll('.tab-button').forEach(btn => btn.classList.remove('active'));
        document.querySelector(`[data-tab="${tabId}"]`).classList.add('active');
        document.querySelectorAll('.tab-content').forEach(c => c.classList.remove('active'));
        document.getElementById(tabId).classList.add('active');
        this.currentTab = tabId;
    }

    async generateModel(type, input) {
        document.getElementById('loading').style.display = 'block';
        try {
            const modelPath = await LocalModelGenerator.generateModel(type, input);
            await this.viewer.loadModel(modelPath);
            this.currentModelUrl = modelPath;
            document.getElementById('result-section').style.display = 'block';
            document.getElementById('result-section').scrollIntoView({ behavior: 'smooth' });
        } catch (error) {
            alert('生成失败: ' + error.message);
        } finally {
            document.getElementById('loading').style.display = 'none';
        }
    }

    downloadModel() {
        if (!this.currentModelUrl) return alert('没有可下载的模型');
        const link = document.createElement('a');
        link.href = this.currentModelUrl;
        link.download = 'generated_model.glb';
        link.click();
    }

    recordFeedback(rating) {
        const feedbackData = { rating, timestamp: new Date().toISOString(), userAgent: navigator.userAgent };
        localStorage.setItem('last_feedback', JSON.stringify(feedbackData));
        alert(`感谢您的反馈！${rating === 'good' ? '👍' : '👎'}`);
    }
}

// 启动应用
document.addEventListener('DOMContentLoaded', () => {
    console.log('🚀 启动3D模型生成器...');
    setTimeout(() => new App(), 100);
});
